<?php 

/**
 * 文章管理
 * @Author      jiating
 * @DateTime    2018-04-14
 */

namespace app\admin\controller;

use app\admin\model\Article as ArticleModel;
use app\admin\model\Articledetail;
use \think\Request;

class Article extends Base{

	public function __construct() {
		parent::__construct();
		$this->model = new ArticleModel();
	}

    public function test(){
        return $this->fetch();
    }

	public function index() {
		$list = $this->model->where('tenantId',session('TENANT_ID'))->order("orderNo")->select();
		$this->assign('list',$list);
		return $this->fetch();
	}

    public function indexApi() {
        $request = Request::instance();
        $param = $request->param();
        $where = ['tenantId'=>session('TENANT_ID')];
        $start = $param['start'];
        $length = $param['length'];

        if(empty($param['search']['value'])) {  //排序展示，默认按排序字段由小到大
            $order = 'orderNo';
        }else{
            $order = json_decode($param['search']['value'],true);
            if($order['order'] == '1') {  //最新发布
                $order = 'createDate DESC';
            } else if($order['order'] == '2'){  //最多预览
                $order = 'readCount DESC';
            }else if($order['order'] == '3'){  //首页推荐
                $order = 'recommendation';
            }else{
                $order = 'orderNo';
            }
        }

        $list = $list = $this->model->where($where)->order($order)->limit($start,$length)->select();

        $count = $this->model->where($where)->count();
        $res = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
            'test' => $param
        ];
        return json($res);
    }

	public function add() {
		return $this->fetch();
	}

	public function save() {
		$request = Request::instance();
        $data = $request->param();
        // return $data;

		if($data['article']['id']) {  //编辑操作
			$data['article']['updateDate'] = date('Y-m-d H:i:s',time());
			$data['article']['updateOper'] = session('member')['id'];
			$add =$this->model->update($data['article']);            
            Articledetail::where(['articleId'=>$data['article']['id']])->update(['detail'=>$data['detail']]);
		} else {  //添加操作
            $id = get_uniqid_id();
            $autoData = [
                'id' => $id,
                'tenantId' => session('TENANT_ID'),
                'createDate' => date('Y-m-d H:i:s',time()),
                'updateDate' => date('Y-m-d H:i:s',time()),
                'createOper' => session('member')['id'],
                'updateOper' => session('member')['id']
            ];
            Articledetail::insert(['articleId'=>$id,'detail'=>$data['detail']]);
            $data = array_merge($data['article'],$autoData);
            $add = $this->model->insert($data);
		}
		if($add) {
			return json(['code'=>'1','message'=>'修改成功']);
        } else {
        	return json(['code'=>'2','message'=>'网络出错，请重试']);
        }
	}

	public function edit() {
		$id = $this->request->param('id');
		$row = $this->model->alias('a')->join('articledetail b','a.id=b.articleId')->where('id',$id)->find();
		$this->assign('row',$row);
		return $this->fetch();
	}

	//弃用
	public function editPost() {
		$data = input('post.');
		$data['updateDate'] = date('Y-m-d H:i:s',time());
		$data['updateOper'] = session('member')['id'];
		$this->model->update($data);
		$this->success('修改成功','index');
	}

	public function sort() {
		$request = Request::instance();
        $post = $request->param();
		$data = [];
        $ids = json_decode($post['id'],true);
        $orders = json_decode($post['order'],true);
		foreach ($ids as $k => $v) {
			$tmp = [
				'id' => $v,
				'orderNo' => $orders[$k]
			];
			$data[] = $tmp;
		}
		foreach ($data as $u) {
			$this->model->update($u);
		}
        return json(['code'=>'1','message'=>'排序成功']);
	}

	/**
	 * 文章-首页推荐
	 * @Author   jiating
	 * @DateTime 2018-05-11
	 */
	public function recommend() {
		$request = Request::instance();
        $id = $request->param('id');

        $row = $this->model->where('id',$id)->find();
        if($row['recommendation'] == 2) {  //设为推荐
        	$data = ['recommendation'=> 1];
        } else {   //取消推荐
        	$data = ['recommendation'=> 2];
        }
        $upd = $this->model->where('id',$id)->update($data);
        if($upd)
            return json(['code'=>'1','message'=>'推荐成功']);
        return json(['code'=>'2','message'=>'出错，请重试']);
	}

	public function delete() {
		$id = $this->request->param('id');

        $where = ['id'=>$id,'tenantId'=>session('TENANT_ID')];

        if($this->model->where($where)->delete() && Articledetail::where('articleId',$id)) {
            return json(['code'=>'1','message'=>'删除成功']);
        } else {
            return json(['code'=>'2','message'=>'网络出错，请重试']);
        }
	}

	public function dialogPage() {
    	return $this->fetch('public:ueditor_dialog');
    }




}